import {useParams} from "react-router-dom";
import {useRequest} from "ahooks";
import {getQuestionService} from "../service/question";
import {useEffect} from "react";
import {useDispatch} from "react-redux";
import {resetComponent} from "../redux/componentsReducer";
import {resetPageInfo} from "../redux/pageinfoReducer";

function useLoadQuestionData() {
  const {id = ''} = useParams()
  const dispatch = useDispatch()
  const {data, loading, run, error} = useRequest(async (id: string) => {
    if (!id) return
    const data = await getQuestionService(id)
    console.log('data', data)
    return data
  }, {
    manual: true
  })
  // 根据获取到的data存储到redux中
  useEffect(() => {
    if (!data) return
    const {title = '', desc = '', js = '', css = '', componentList = []} = data
    let selectedId = ''
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id
    }
    dispatch(resetComponent({componentList, selectedId, copyComponent: null}))
    dispatch(resetPageInfo({title, desc, js, css}))
  }, [data]);

  //问卷id变化时，自动加载问卷数据
  useEffect(() => {
    run(id)
  }, [id]);
  return {
    loading,
    data,
    error
  }
}

export default useLoadQuestionData
